
package com.zcp.pcsuitall.business;

import com.zcp.pcsuitall.Action;
import com.zcp.pcsuitall.BusinessControl;
import com.zcp.pcsuitall.IDealWithMessage;
import com.zcp.pcsuitall.SuitUtil;
import com.zcp.pcsuitall.XmlDataDealWith;

import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Xml;

import java.io.StringWriter;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

public class SystemInfoManager implements IDealWithMessage {

    // android.os.Build.VERSION.SDK_INT对应的版本号。
    private static String[] versionstr = {
            "Android 1.0", "Android 1.0", "Android 1.1", "Android 1.5", "Android 1.6",
            "Android 2.0", "Android 2.0.1", "Android 2.1", "Android 2.2", "Android 2.3",
            "Android 2.3.3", "Android 3.0", "Android 3.1", "Android 3.2", "Android 4.0","Android 4.0"
    };

    @Override
    public boolean dealWith(SocketChannel sc, Action action, Context context) {

        if ("LoadStateInfo".equals(action.getName())) {
            return dealWithGetStateInfo(context, sc, action);
        } else if ("LoadSystemInfo".equals(action.getName())) {
            return dealWithGetSystemInfo(context, sc, action);
        } else if ("CheckKey".equals(action.getName())) {
            return dealWithCheckKey(context, sc, action);
        } else {
            return false;
        }
    }

    private boolean dealWithGetStateInfo(Context context, SocketChannel sc, Action action) {
        StringWriter writer = new StringWriter();
        XmlSerializer serializer = Xml.newSerializer();
        try {
            serializer.setOutput(writer);
            XmlDataDealWith.createPre(action, serializer);

            long[] imageInfo = SuitUtil.getImageNumber(context,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            long[] innerImageInfo = SuitUtil.getImageNumber(context,
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
//             long picCount = imageInfo[0] + innerImageInfo[0];
            long picCount = imageInfo[0];
            long picTotalSize = imageInfo[1];
            long innerPicTotalSize = innerImageInfo[1];

            long[] videoInfo = SuitUtil.getVideoNumber(context,
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
            long[] innerVideoInfo = SuitUtil.getVideoNumber(context,
                    MediaStore.Video.Media.INTERNAL_CONTENT_URI);
            long videoCount = videoInfo[0] + innerVideoInfo[0];
            long videoTotalSize = videoInfo[1];
            long innerVideoTotalSize = innerVideoInfo[1];

            long[] audioInfo = SuitUtil.getAudioNumber(context,
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
            long[] innerAudioInfo = SuitUtil.getAudioNumber(context,
                    MediaStore.Audio.Media.INTERNAL_CONTENT_URI);

            // long audioCount = audioInfo[0] + innerAudioInfo[0];
            long audioCount = audioInfo[0];
            long audioTotalSize = audioInfo[1];
            long innerAudioTotalSize = innerAudioInfo[1];

            int contactCount = SuitUtil.getAllContactCount(context);

            int smsCount = SuitUtil.getAllSmsCount(context);

            long[] sdcardSpace = SuitUtil.getSdAvailableSpace();

            long[] systemSpace = SuitUtil.getSystemAvailableSpace();

            // 设置图片数量。
            serializer.startTag("", "pic_count");
            serializer.text(String.valueOf(picCount));
            serializer.endTag("", "pic_count");

            // 设置视频数量。
            serializer.startTag("", "video_count");
            serializer.text(String.valueOf(videoCount));
            serializer.endTag("", "video_count");

            // 设置音频数量。
            serializer.startTag("", "audio_count");
            serializer.text(String.valueOf(audioCount));
            serializer.endTag("", "audio_count");

            // 设置联系人数量。
            serializer.startTag("", "contact_count");
            serializer.text(String.valueOf(contactCount));
            serializer.endTag("", "contact_count");

            // 设置短信数量。
            serializer.startTag("", "sms_count");
            serializer.text(String.valueOf(smsCount));
            serializer.endTag("", "sms_count");

            int[] counts = SuitUtil.getAppNumber(context);
            // 系统应用程序。
            serializer.startTag("", "sys_app_count");
            serializer.text(String.valueOf(counts[0]));
            serializer.endTag("", "sys_app_count");

            // 用户应用程序。
            serializer.startTag("", "user_app_count");
            serializer.text(String.valueOf(counts[1]));
            serializer.endTag("", "user_app_count");

            // anroid 内部存储空间
            serializer.startTag("", "phonespace");

            serializer.startTag("", "total");
            serializer.text(systemSpace[1] + "");
            serializer.endTag("", "total");

            serializer.startTag("", "pic");
            serializer.text(innerPicTotalSize + "");
            serializer.endTag("", "pic");

            serializer.startTag("", "video");
            serializer.text(innerVideoTotalSize + "");
            serializer.endTag("", "video");

            serializer.startTag("", "music");
            serializer.text(innerAudioTotalSize + "");
            serializer.endTag("", "music");

            long innerOther = systemSpace[1] - systemSpace[0] - innerPicTotalSize
                    - innerVideoTotalSize - innerAudioTotalSize;

            serializer.startTag("", "other");
            serializer.text(innerOther + "");
            serializer.endTag("", "other");

            serializer.endTag("", "phonespace");

            // sd卡信息
            serializer.startTag("", "sdspace");

            serializer.startTag("", "total");
            serializer.text(sdcardSpace[1] + "");
            serializer.endTag("", "total");

            serializer.startTag("", "pic");
            serializer.text(picTotalSize + "");
            serializer.endTag("", "pic");

            serializer.startTag("", "video");
            serializer.text(videoTotalSize + "");
            serializer.endTag("", "video");

            serializer.startTag("", "music");
            serializer.text(audioTotalSize + "");
            serializer.endTag("", "music");

            serializer.startTag("", "other");
            long other = sdcardSpace[1] - sdcardSpace[0] - picTotalSize - videoTotalSize
                    - audioTotalSize;
            serializer.text(other + "");
            serializer.endTag("", "other");

            serializer.endTag("", "sdspace");

            serializer.endTag("", "data");
            serializer.endTag("", "root");
            serializer.endDocument();
            BusinessControl.returnToClient(sc, writer.toString(), context);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()), context);
            return false;
        }
    }

    /**
     * 处理获取系统信息。
     * 
     * @param context
     * @param sc
     * @param action
     * @return
     */
    private boolean dealWithGetSystemInfo(Context context, SocketChannel sc, Action action) {
        try {
            if (tm == null) {
                tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            }
            LinkedList<String> systems = new LinkedList<String>();
            String deviceId = tm.getDeviceId();

            systems.add(deviceId == null ? "" : deviceId);
            systems.add(android.os.Build.MODEL != null ? android.os.Build.MODEL : "");
            String result = packageData(action, systems, context);

            BusinessControl.returnToClient(sc, result, context);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()), context);
            return false;
        }
    }

    /**
     * 判断WIFI连接后，客户端发送过来的密钥是否正确
     * 
     * @param context
     * @param sc
     * @param action
     * @return
     */
    private boolean dealWithCheckKey(Context context, SocketChannel sc, Action action) {
        try {
            String remoteKey = XmlDataDealWith.getRegularSingle("key", action.getSource());
            SharedPreferences shPre = context.getSharedPreferences("PcSuitPhone",
                    Context.MODE_PRIVATE);
            String localKey = shPre.getString("cipherKey", "");
            String result = "<?xml version='1.0' encoding='utf-8'?><root><action>CheckKey</action><data><result>"
                    + remoteKey.equals(localKey) + "</result></data></root>";
            BusinessControl.returnToClient(sc, result, context);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()), context);
            return false;
        }

    }

    /**
     * 获取系统类型、设备ID、图片数量、视频数量、音频数量、联系人总数、短信总数。
     * 
     * @param action
     * @param systems
     * @return
     */
    protected String packageData(Action action, LinkedList<String> systems, Context context) {
        StringWriter writer = new StringWriter();
        XmlSerializer serializer = Xml.newSerializer();
        try {
            serializer.setOutput(writer);
            XmlDataDealWith.createPre(action, serializer);
            if (systems != null) {
                // serializer.startTag("", "item");

                serializer.startTag("", "type");
                serializer.text(systems.get(1));
                serializer.endTag("", "type");

                serializer.startTag("", "device_id");
                serializer.text(systems.get(0));
                serializer.endTag("", "device_id");

                serializer.startTag("", "osVersion");
                serializer.text("Android "+android.os.Build.VERSION.RELEASE);
                serializer.endTag("", "osVersion");

                serializer.startTag("", "assistVersion");
                serializer.text(context.getPackageManager().getPackageInfo("com.zcp.pcsuitall",
                        PackageManager.GET_UNINSTALLED_PACKAGES).versionName);
                serializer.endTag("", "assistVersion");
                // serializer.endTag("", "item");

            }

            serializer.endTag("", "data");
            serializer.endTag("", "root");
            serializer.endDocument();
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return XmlDataDealWith.getSystemErrorString(action.getName(), e.toString());
        }

    }

    private TelephonyManager tm = null;

}
